package cooltcp;

import java.io.*;
import java.net.*;

public class SimpleTcpServer {

	private ServerSocket simpleserver = null;
	private SaveImage savei = null;
	
	private static final int bindPort = 11111; //evt hardcoded var mi?
	private static final int MAX_IO_BUFF = 4096;
	
	private BufferedInputStream server_bi = null;
    private DataInputStream server_di =null;

	
	public SimpleTcpServer() throws IOException{
		this.savei = new SaveImage();  //open it to stay here for a while ...
		
	}
	
	public void runServer() throws  IOException{
		
		//bind the server please
		this.simpleserver = new ServerSocket(this.bindPort);
		
		System.out.println("The server is started on port :"+this.bindPort);
		//create a client socket
		Socket client_connection = null;
		client_connection = this.simpleserver.accept(); // it waits here some data comes
	
		//you can retrieve data with these
		this.server_bi = new BufferedInputStream(client_connection.getInputStream());
		this.server_di = new DataInputStream(this.server_bi);
		
		//we wont write data for now ... later maybe
		byte[] byte_seq = new byte[this.MAX_IO_BUFF]; //allocate for that
		int temp_result=0;
		
		while((temp_result=this.server_di.read(byte_seq, 0, MAX_IO_BUFF))!=-1){
			
			//the data is stored into byte_array so we should copy it
			try{
				this.savei.writeThatByte(byte_seq,this.MAX_IO_BUFF); // save the byte array
			}
			catch (IOException e) {
				System.err.println("Error in saving the retrieved data");
				System.exit(1);
			}
		}
		
		System.out.println("The server is shutting down");
		
	}
	
	public static void main(String[] args){
		
		//the executable part
		
	}
	
}
